package cn.yunhe.controller;

import cn.yunhe.entity.Transaction;
import cn.yunhe.validate.TransactionValidate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.DataBinder;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.List;

@Controller
public class ValidateController {

    @RequestMapping("/vali")
    public ModelAndView vali(@Valid Transaction transaction, Errors errors) {
        if (errors.hasErrors()) {
            //将错误提示信息放到 fieldErrors集合中
            List<FieldError> fieldErrors = errors.getFieldErrors();

            for (FieldError f : fieldErrors) {
                System.out.println("字段：" + f.getField() + ",提示信息：" + f.getDefaultMessage());

            }
        }
        ModelAndView mv = new ModelAndView();
        mv.addObject("transaction", transaction);
        mv.setViewName("hello");
        return mv;
    }


    public void initBinder(DataBinder binder) {
        binder.setValidator(new TransactionValidate());
    }
}
